package com.ibiaoke.pay;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.ibiaoke.common.configs.WeChatConfigs;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.utils.IPUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class BkWeChatPayClient {
    private Logger logger = Logger.getLogger(this.getClass().getName());

    public Map<String, String> wxPay(String openId, String body, String out_trade_no, String total_fee, String trade_type, String notify_url) {
        String spbill_create_ip = IPUtil.getIp();
        Map<String, String> data = new HashMap<>();
        data.put("body", body); // 订单标签
        data.put("out_trade_no", out_trade_no); //订单号（本地数据库中）
        data.put("total_fee", total_fee);  //订单金额
        data.put("spbill_create_ip", spbill_create_ip); //ip
        data.put("notify_url", notify_url);    //回调方法的地址
        data.put("trade_type", trade_type);  // 此处指定为公众号支付 JSAPI
        data.put("openid", openId);         //保存在session的openid
        try {
            WXPay wxPay = new WXPay(new WXPayConfigImpl());
            Map<String, String> unifiedOrderRes = wxPay.unifiedOrder(data);
            return toJsapiPayParam(unifiedOrderRes);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    private Map<String, String> toJsapiPayParam(Map<String, String> unifiedOrderRes) throws Exception {
        if(unifiedOrderRes.get("prepay_id")!=null){
            String prepay_id = unifiedOrderRes.get("prepay_id");
            Map<String,String> jsapiPayParam=new HashMap<>();
            jsapiPayParam.put("appId", "wx0d915580d35937a3");
            jsapiPayParam.put("timeStamp", String.valueOf(System.currentTimeMillis()/1000));
            jsapiPayParam.put("nonceStr", WXPayUtil.generateNonceStr());
            jsapiPayParam.put("package","prepay_id="+prepay_id);
            jsapiPayParam.put("signType","MD5");
            String sign = WXPayUtil.generateSignature(jsapiPayParam, "38497d9c935dcf4e25381552dd6e2948", WXPayConstants.SignType.MD5);
            jsapiPayParam.put("paySign",sign);
            return jsapiPayParam;
        }else if(unifiedOrderRes.get("err_code_des")!=null){
            logger.error(JSONObject.toJSONString(unifiedOrderRes));
            throw new ServiceException(unifiedOrderRes.get("err_code_des"));
        }else{
            logger.error(JSONObject.toJSONString(unifiedOrderRes));
            throw new ServiceException("微信支付出错");
        }
    }


    /**
     * 申请退款
     * 服务商模式接入文档:https://pay.weixin.qq.com/wiki/doc/api/micropay_sl.php?chapter=9_4
     * 商户模式接入文档:https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_4
     *
     * @param params
     *            请求参数
     * @return
     */
    public static Map<String, String> orderRefund(Map<String, String> params) {
        WXPay wxPay = new WXPay(new WXPayConfigImpl());
        try {
            return  wxPay.refund(params);
        } catch (Exception e) {
            throw new ServiceException("微信退款失败",e);
        }
    }
}
